#!/bin/sh 

# name:			audio converter
# brief:		convert single file
# license:	http://www.gnu.org/licenses/lgpl-3.0.txt
# author:		manifest

output_codec() {
	case $1 in
		"mp3")	echo "libmp3lame";;
		"wma")	echo "wmav2";;
		"aac")	echo "libfaac";;
		"alac")	echo "alac";;
		"flac")	echo "flac";;
		*)			error "unsupported output format";;
	esac
}

output_ext() {
	case $1 in
		"mp3")	echo "mp3";;
		"wma")	echo "wma";;
		"aac")	echo "aac";;
		"alac")	echo "m4a";;
		"flac")	echo "flac";;
		*)			error "unsupported output format";;
	esac
}

usage() {
	echo "USAGE: `basename $0` [-i input file] [-o output format] [-ab bitrate_param] [-ar frequency_param] [-ac channels_param] [-ss start_param] [-t duration_param]";
	exit 1;
}

error() {
	echo "ERROR: $1"
	usage
}

input_file=
output_format=
params=

while :
do
	case "$1" in
		-i)		shift; input_file="$1";;
		-o)		shift; output_format="$1";;
		-ab)	shift; params="$params -ab $1";;
		-ar)	shift; params="$params -ar $1";;
		-ac)	shift; params="$params -ac $1";;
		-ss)	shift; params="$params -ss $1";;
		-t)		shift; params="$params -t $1";;
		-*)	usage;;
		*)	break;;
	esac
	shift
done

if [ ! "$input_file" ]; then
	error "input file not set"
fi

if [ ! "$output_format" ]; then
	error "output format not set"
fi

input_file_ext=`expr "$input_file" : '.*\.\(.*\)'`
output_codec=`output_codec "$output_format"`
output_file_ext=`output_ext "$output_format"`
output_file=`basename "$input_file" ."$input_file_ext"`."$output_file_ext"

ffmpeg -i "$input_file" -vn -acodec "$output_codec" $params "$output_file"

